package com.mybatisplus.controller;

import com.mybatisplus.entity.BaseResultBean;
import com.mybatisplus.utils.QrCodeUtil;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author: GuoZhengrong
 * @Created: 2023/4/10 20:31
 */

@RestController
@RequestMapping("/QrCode")
public class QrCodeController {
    @GetMapping("/getQrCode")
    public BaseResultBean getQrCode(HttpServletRequest request, HttpServletResponse response) {
        BaseResultBean resultBean = new BaseResultBean();
        SimpleDateFormat format = new SimpleDateFormat("YYYY_MM_dd_HH_mm_ss");//指定日期格式
        Date now = new Date();
        resultBean.setStatus(true);
        resultBean.setMessage("生成成功");
        StringBuilder builder = new StringBuilder(request.getParameter("content"));//获取参数名为content的值
        try {
            QrCodeUtil.createCodeToOutputStream(builder.toString(), response.getOutputStream());//发出响应，将二维码image流返回给浏览器，建议用img标签进行发送请求。
        } catch (IOException e) {
            //出现错误时将返回500
            try {
                response.sendError(500, "生成二维码失败!");
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
            BaseResultBean fail = new BaseResultBean();
            fail.setMessage(e.getMessage());
            fail.setStatus(false);
            return fail;
        }
        return resultBean;
    }
}
